import { asyncRoutes, constantRoutes, getMenu } from '@/router'
import { menuList } from '@/api/login'

// 确定当前用户是否具有权限, roles是数组,route是当前路由对象
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// 过滤异步路由表   routes asyncRoutes,,  roles
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes // 动态可访问的路由 数组
    state.routes = constantRoutes.concat(routes) // 无需判断权限的路由数组和 动态可访问的路由  合集
    // console.log(state.routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes // 存放: 动态可访问的路由 和  后端返回的路由数组
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || [] // 如果有admin角色,,则把动态可访问的路由 全都放入accessedRoutes
      }
      else {
        let permsId_list = JSON.parse(window.localStorage.getItem('permsId_list'))
        accessedRoutes = getMenu(permsId_list)   // 根据权限取路由列表(过滤)
        // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) // 根据权限 获取路由列表(过滤)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
